package com.myapidemos;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.myapidemos.R;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MyApiDemos extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);

		String prefix = getIntent().getStringExtra("com.myapidemos.apis.Path");
		if (prefix == null) {
			prefix = "";
		}

		ListView view = (ListView) findViewById(R.id.mainListView);
		view.setAdapter(new MyListViewAdapter(getMyData(prefix)));
		view.setTextFilterEnabled(true);
		view.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
				Intent intent = (Intent) map.get("intent");
				startActivity(intent);
			}
		});
	}

	private List<Map<String, Object>> getMyData(String prefix) {
		List<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();

		String[] prefixPath;
		String prefixWithSlash = prefix;
		if (prefix.equals("")) {
			prefixPath = null;
		} else {
			prefixPath = prefix.split("\\.");
			prefixWithSlash = prefix + ".";
		}

		Intent mainIntent = new Intent();
		mainIntent.setAction(Intent.ACTION_MAIN);
		PackageManager pm = getPackageManager();
		mainIntent.setPackage("com.example.myapidemos");
		mainIntent.addCategory(Intent.CATEGORY_SAMPLE_CODE);

		List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

		if (list == null) {
			return myData;
		}

		Map<String, Boolean> entites = new HashMap<String, Boolean>();
		for (ResolveInfo info : list) {
			String label = info.activityInfo.name.substring(20);

			if (prefixWithSlash.length() == 0 || label.startsWith(prefixWithSlash)) {
				String[] labelPath = label.split("\\.");
				String nextLabel = (prefixPath == null ? labelPath[0]
						: labelPath[prefixPath.length]);

				if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
					addItem(myData,
							nextLabel,
							activityIntent(info.activityInfo.applicationInfo.packageName,
									info.activityInfo.name));
				} else {
					if (entites.get(nextLabel) == null) {
						addItem(myData, nextLabel, browseIntent(prefix.equals("") ? nextLabel
								: prefix + "." + nextLabel));
						entites.put(nextLabel, true);
					}
				}
			}
		}
		Collections.sort(myData, sDisplayNameComparator);
		return myData;
	}

	class MyListViewAdapter extends BaseAdapter {

		private List<Map<String, Object>> data;

		private LayoutInflater inflater;

		public MyListViewAdapter(List<Map<String, Object>> data) {
			inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = new View(MyApiDemos.this);
			}
			convertView = inflater.inflate(R.layout.main_view, null);
			// ImageView image = (ImageView)
			// convertView.findViewById(R.id.main_icom);
			TextView text = (TextView) convertView.findViewById(R.id.main_label);

			// int iconId;
			// Intent intent = (Intent) data.get(position).get("intent");
			// if
			// (intent.getComponent().getClassName().equals(MyApiDemos.class.getName()))
			// {
			// iconId = R.drawable.folder;
			// } else {
			// iconId = R.drawable.ic_launcher;
			// }
			// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
			// iconId);
			// image.setImageBitmap(bitmap);

			text.setText((CharSequence) data.get(position).get("title"));
			return convertView;
		}

	}

	private final static Comparator<Map<String, Object>> sDisplayNameComparator = new Comparator<Map<String, Object>>() {
		private final Collator collator = Collator.getInstance();

		public int compare(Map<String, Object> map1, Map<String, Object> map2) {
			return collator.compare(map1.get("title"), map2.get("title"));
		}
	};

	protected Intent activityIntent(String pkg, String componentName) {
		Intent result = new Intent();
		result.setClassName(pkg, componentName);
		return result;
	}

	protected Intent browseIntent(String path) {
		Intent result = new Intent();
		result.setClass(this, MyApiDemos.class);
		result.putExtra("com.myapidemos.apis.Path", path);
		return result;
	}

	protected void addItem(List<Map<String, Object>> data, String name, Intent intent) {
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("title", name);
		temp.put("intent", intent);
		data.add(temp);
	}
}
